package pl.bristleback.bindingsample.actions;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.token.Token;
import pl.bristleback.bindingsample.vo.User;
import pl.bristleback.server.bristle.actions.AnnotatedRemoteAction;
import pl.bristleback.server.bristle.actions.RemoteAction;
import pl.bristleback.server.bristle.binding.Bind;
import pl.bristleback.server.bristle.binding.ObjectBinder;
import pl.bristleback.server.bristle.binding.Property;
import pl.bristleback.server.bristle.exceptions.BindingException;
import pl.bristleback.server.bristle.messages.MessageSendersExporter;
import pl.bristleback.server.bristle.messages.SimpleConnectorMessageSender;
import pl.bristleback.server.bristle.utils.BristleTokenFactory;
import pl.bristleback.server.bristle.utils.JsonUtil;

/**
 * //@todo class description
 * <p/>
 * Created on: 2011-03-22 23:33:12 <br/>
 *
 * @author Wojciech Niemiec
 */
@AnnotatedRemoteAction(actionName = "registerAction")
public class BindingFormAction implements RemoteAction {
  private static Logger log = Logger.getLogger(BindingFormAction.class.getName());

  @Bind(rootName = "registerForm", properties = {
    @Property(name = "sex", required = true),
    @Property(name = "firstName", required = true),
    @Property(name = "surname", required = true),
    @Property(name = "age"),
    @Property(name = "favouriteBands.name"),
    @Property(name = "favouriteBands.genre"),
    @Property(name = "accountBalance"),
    @Property(name = "vehicles")
  })
  private ObjectBinder<User> formBinder;


  public void performAction(WebSocketConnector connector, Token token) {
    SimpleConnectorMessageSender messageSender = (SimpleConnectorMessageSender) MessageSendersExporter.getMessageSender(SimpleConnectorMessageSender.SENDER_NAME);
    try {
      User user = formBinder.bind(token);
      Token correctResponse = BristleTokenFactory.createJsonResponseToken(token, JsonUtil.getJsonFromBean(user, true));
      messageSender.sendMessage(correctResponse, connector);
    } catch (BindingException e) {
      Token exceptionResponse = BristleTokenFactory.createValidationExceptionToken(token, e.getBindingResult());
      messageSender.sendMessage(exceptionResponse, connector);
    } catch (JSONException e) {
      log.error("Unexpected json exception", e);
    }
  }
}
